package com.hlkj.warboot.configurer.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * @Description:
 * @Author: lixing
 * @Date: 2020/11/2 17:11
 */
public class RSAUtil2 {

    /**
     * RSA最大加密明文大小
     */
    private static final int MAX_ENCRYPT_BLOCK = 117;

    /**
     * RSA最大解密密文大小
     */
    private static final int MAX_DECRYPT_BLOCK = 128;

    /**
     * 获取密钥对
     *
     * @return 密钥对
     */
    public static KeyPair getKeyPair() throws Exception {
        KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
        generator.initialize(1024);
        return generator.generateKeyPair();
    }

    /**
     * 获取私钥
     *
     * @param privateKey 私钥字符串
     * @return
     */
    public static PrivateKey getPrivateKey(String privateKey) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] decodedKey = Base64.decodeBase64(privateKey.getBytes());
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedKey);
        return keyFactory.generatePrivate(keySpec);
    }

    /**
     * 获取公钥
     *
     * @param publicKey 公钥字符串
     * @return
     */
    public static PublicKey getPublicKey(String publicKey) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] decodedKey = Base64.decodeBase64(publicKey.getBytes());
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decodedKey);
        return keyFactory.generatePublic(keySpec);
    }

    /**
     * @Description TODO 公钥加密 + 私钥解密
     * @Author lixing
     * @Date 2020/11/2 17:32
     */
    /**
     * 公钥加密
     * @param data      待加密数据
     * @param publicKey 公钥
     * @return
     */
    public static String encryptByPublicKey(String data, PublicKey publicKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        int inputLen = data.getBytes().length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offset = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段加密
        while (inputLen - offset > 0) {
            if (inputLen - offset > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(data.getBytes(), offset, MAX_ENCRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(data.getBytes(), offset, inputLen - offset);
            }
            out.write(cache, 0, cache.length);
            i++;
            offset = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();
        // 获取加密内容使用base64进行编码,并以UTF-8为标准转化成字符串
        // 加密后的字符串
        return Base64.encodeBase64String(encryptedData);
    }
    /**
     * 私钥解密
     * @param data       待解密数据
     * @param privateKey 私钥
     * @return
     */
    public static String decryptByPrivateKey(String data, PrivateKey privateKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] dataBytes = Base64.decodeBase64(data);
        int inputLen = dataBytes.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offset = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段解密
        while (inputLen - offset > 0) {
            if (inputLen - offset > MAX_DECRYPT_BLOCK) {
                cache = cipher.doFinal(dataBytes, offset, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(dataBytes, offset, inputLen - offset);
            }
            out.write(cache, 0, cache.length);
            i++;
            offset = i * MAX_DECRYPT_BLOCK;
        }
        byte[] decryptedData = out.toByteArray();
        out.close();
        // 解密后的内容
        return new String(decryptedData, StandardCharsets.UTF_8);
    }

    /**
     * 签名
     * @param data       待签名数据
     * @param privateKey 私钥
     * @return 签名
     */
    public static String signByPrivateKey(String data, PrivateKey privateKey) throws Exception {
        byte[] keyBytes = privateKey.getEncoded();
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey key = keyFactory.generatePrivate(keySpec);
        Signature signature = Signature.getInstance("MD5withRSA");
        signature.initSign(key);
        signature.update(data.getBytes());
        return new String(Base64.encodeBase64(signature.sign()));
    }

    /**
     * 验签
     * @param data   原始字符串
     * @param publicKey 公钥
     * @param sign      签名
     * @return 是否验签通过
     */
    public static boolean verifyByPublicKey(String data, PublicKey publicKey, String sign) throws Exception {
        byte[] keyBytes = publicKey.getEncoded();
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey key = keyFactory.generatePublic(keySpec);
        Signature signature = Signature.getInstance("MD5withRSA");
        signature.initVerify(key);
        signature.update(data.getBytes());
        return signature.verify(Base64.decodeBase64(sign.getBytes()));
    }

    /**
     * @Description TODO 私钥加密 + 公钥解密
     * @Author lixing
     * @Date 2020/11/2 17:32
     */
    /**
     * 私钥加密
     * @param data      待加密数据
     * @param privateKey 私钥
     * @return
     */
    public static String encryptByPrivateKey(String data, PrivateKey privateKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);
        int inputLen = data.getBytes().length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offset = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段加密
        while (inputLen - offset > 0) {
            if (inputLen - offset > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(data.getBytes(), offset, MAX_ENCRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(data.getBytes(), offset, inputLen - offset);
            }
            out.write(cache, 0, cache.length);
            i++;
            offset = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();
        // 获取加密内容使用base64进行编码,并以UTF-8为标准转化成字符串
        // 加密后的字符串
        return Base64.encodeBase64String(encryptedData);
    }
    /**
     * 公钥解密
     * @param data       待解密数据
     * @param publicKey  公钥
     * @return
     */
    public static String decryptByPublicKey(String data, PublicKey publicKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, publicKey);
        byte[] dataBytes = Base64.decodeBase64(data);
        int inputLen = dataBytes.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offset = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段解密
        while (inputLen - offset > 0) {
            if (inputLen - offset > MAX_DECRYPT_BLOCK) {
                cache = cipher.doFinal(dataBytes, offset, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(dataBytes, offset, inputLen - offset);
            }
            out.write(cache, 0, cache.length);
            i++;
            offset = i * MAX_DECRYPT_BLOCK;
        }
        byte[] decryptedData = out.toByteArray();
        out.close();
        // 解密后的内容
        return new String(decryptedData, StandardCharsets.UTF_8);
    }

    /**
     * @Description TODO 测试
     * @Author lixing
     * @Date 2020/11/2 17:33
     */
    public static void main(String[] args) {
        try {
            String data = "{\"timeStamp\":\"20201102100951\",\"busiDataReq\":{\"phoneNo\":\"phoneNo\",\"orderNo\":\"orderNo\",\"busType\":\"busType\",\"orderType\":\"orderType\",\"Sign\":\"Sign\",\"remark\":\"remark\",\"D2\":\"D2\",\"T1\":\"2020-11-01 10:00:00\"}}";
            data = JSONObject.parse(data).toString();
            // 生成密钥对
            KeyPair keyPair = getKeyPair();
            String privateKey = new String(Base64.encodeBase64(keyPair.getPrivate().getEncoded()));
            String publicKey = new String(Base64.encodeBase64(keyPair.getPublic().getEncoded()));
            publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCLYmFJRKBmkvZIaz/Qob///JcGdf2yXNGpW0cuvQfm5FY5uvV8uzQJv0fdNyAWHPT+FFwWsLJZWm03gkb1c47jt69j9A6lA19e+0zIcfoCMLIViUW6CsPu+oa45viJSybZ7Bonp085gaOgM18Y+//A+0IETqfxKXNui+lD8o2vsQIDAQAB";
            privateKey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAItiYUlEoGaS9khrP9Chv//8lwZ1/bJc0albRy69B+bkVjm69Xy7NAm/R903IBYc9P4UXBawsllabTeCRvVzjuO3r2P0DqUDX177TMhx+gIwshWJRboKw+76hrjm+IlLJtnsGienTzmBo6AzXxj7/8D7QgROp/Epc26L6UPyja+xAgMBAAECgYAKWELgLTe6ZS3iMhOKaHbXiOeskxVBJ6Jn715ZGa58dHXx0u5lU3+JOakbwfufqIaGVPyAspyKBSwV8pVRokH4iJ9dzMGhVTg7Qwe6bE605qduFwFzG0xhHR95bkFTB8C52hQueEs3KbHDmTvuXhaHpU8MyrnVLxXftP9qVvsAAQJBALz6efJVw28+Gx7yuoKxibo/8EPfDkU5uCWMJyjox555OuBfe+BRgNchHvw+jYZcI6dwYkESAtj+Z7/ZlU/pGPECQQC80TUofTE31krY03Od9eFxlhs/h9Kt/O3pKIpIcV+DN6RfM3v2ezk/70dfkqvGOTUgGRn1qHZEFe6lXt/7oALBAkAeyxXJ5i21V8JllZnMqA9QORD2jkcuAoy+GYtcACpe6VQtsYFm+QDsjSoWYj7/cM4if46TGdM69qGDQnoxDkORAkEAmBeU0DZ3zNhqldlNyjFjFZGqBTSs+cVBBozHRq88FoBdgOoBsntzlBJz1YJZp2QxbNeLV5wJF7Lq9n5DwXYUgQJBAKzcmeCZhL6iyEYcOPIjoAb3ueycljdysIsa70LrwdVvKlBSOmPeygtLUQYvEEzkb/5kQBnlwBrO4trzjA9F464=";
            System.out.println("私钥:" + privateKey);
            System.out.println("公钥:" + publicKey);
            System.out.println("");
            //
            //
            // 公钥加密
            String encryptData = encryptByPublicKey(data, getPublicKey(publicKey));
            System.out.println("公钥加密后内容:" + encryptData);
            // 私钥解密
            String decryptData = decryptByPrivateKey(encryptData, getPrivateKey(privateKey));
            System.out.println("私钥解密后内容:" + decryptData);
            // RSA签名
            String sign = signByPrivateKey(data, getPrivateKey(privateKey));
            // RSA验签
            boolean result = verifyByPublicKey(data, getPublicKey(publicKey), sign);
            System.out.println("验签结果:" + result);
            System.out.println("");
            //
            //
            // 私钥加密
            String encryptData2 = encryptByPrivateKey(data, getPrivateKey(privateKey));
            System.out.println("私钥加密后内容:" + encryptData2);
            // 公钥解密
            String decryptData2 = decryptByPublicKey(encryptData2, getPublicKey(publicKey));
            System.out.println("公钥解密后内容:" + decryptData2);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.print("加解密异常");
        }
    }

}
